package com.doitedu.mr.day03;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @Date 2021/12/1
 * @Created by HANGGE
 * @Description TODO
 */
public class Line {
    //Mapper
    static  class LineMapper extends Mapper<LongWritable , Text, IntWritable ,IntWritable>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            try {
                // 2,4
                //1,6
                String line = value.toString();
                String[] split = line.split(","); //  2,4   1 2 3 4 5 6
                //截取点
                int x1 = Integer.parseInt(split[0]);
                int x2 = Integer.parseInt(split[1]);
                // 生成线段经过的点
                for(int i=x1 ; i<=x2 ;i++){
                    IntWritable k = new IntWritable(i);
                    IntWritable v = new IntWritable(1);
                    context.write(k,v);
                }
                // 最大异常
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    //Reducer
    static  class  LineReducer extends Reducer<IntWritable , IntWritable , IntWritable , IntWritable>{
        @Override
        protected void reduce(IntWritable key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int cnt = 0 ;
            for (IntWritable value : values) {
                cnt ++ ;
            }
            IntWritable v = new IntWritable(cnt);
            context.write(key , v);

        }
    }


    public static void main(String[] args) throws  Exception {
        // Job  统计文件中单词出现的次数
        Configuration conf = new Configuration();
        // 1  创建 JOB
        Job job = Job.getInstance(conf, "wordcount");
        // 1) Mapper 类
        job.setMapperClass(LineMapper.class);
        // 2) Reducer类
        job.setReducerClass(LineReducer.class);
        // 3)  设置map输出的数据类型
        job.setMapOutputKeyClass(IntWritable.class);
        job.setMapOutputValueClass(IntWritable.class);
        // 4)  设置reduce输出的数据类型
        job.setOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(IntWritable.class);
        // 5) 设置输入的数据路径
        FileInputFormat.setInputPaths(job , new Path("E:\\mrdata\\line\\input"));
        // 6) 设置输出的结果保存路径
        FileOutputFormat.setOutputPath(job, new Path("E:\\mrdata\\line\\res2"));
        // 2 提交工作
        // 等待执行完成 , 打印执行过
        job.waitForCompletion(true) ;





    }

}
